"""
算法
"""

from os import path
import random
import duckdb
from lucky_draw_api.config import duckdb_file_name, duckdb_file_path


duckdb_dir: str = path.join(duckdb_file_path, duckdb_file_name)

def get_already_draw() -> tuple[list[int], Exception | None]:
    """
    获取已经抽过的号码
    
    - 返回值:
        - 第一个元素: 已经抽过的号码
        - 第二个元素: 错误信息
    """
    try:
        with duckdb.connect(database=duckdb_dir, read_only=True) as conn:
            already_draw_with_tuple = conn.execute("SELECT draw_id FROM lucky_draw").fetchall()
            already_draw = [draw_tuple[0] for draw_tuple in already_draw_with_tuple]
            return already_draw, None
    except Exception as e:
        print(e)
        return [], e


def insert_lucky_draw(*, draw_id: int) -> Exception | None:
    """
    插入抽奖结果
    
    - 参数
        - draw_id: 抽中的学生的学号
    
    - 返回值
        - error: 错误信息，如果为None则表示成功
    """
    try:
        with duckdb.connect(database=duckdb_dir) as conn:
            conn.execute(
                f"""
                INSERT INTO lucky_draw (draw_id)
                VALUES ({draw_id});
                """
            )
    except Exception as e:
        print(e)
        return e
    
    return None


def lucky_draw() -> tuple[int, Exception | None]:
    """
    抽奖
    
    - 返回值:
        - 抽中的学生的学号
        - 抽奖失败的异常信息
    """

    already_draw: list[int]
    err: Exception | None
    already_draw, err = get_already_draw()
    if err:
        return 0, err
    
    if len(already_draw) == 30:
        return 0, Exception("抽奖人数已满")
    
    while True:
        rand_int: int = random.randint(1, 30)
        if rand_int not in already_draw:
            err = insert_lucky_draw(draw_id=rand_int)
            if err:
                return 0, err
            return rand_int, None
    

    